package com.sunrise.xdoc.converters;

import java.text.DecimalFormat;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.YearMonth;

/**
 * 
 * @author PhanHongPhuc
 * 
 */
@FacesConverter("yearMonthConverter")
public class YearMonthConverter implements Converter {

	private static final char SEPARATOR = '-';

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		String[] v = StringUtils.split(value, SEPARATOR);
		return new YearMonth(Integer.valueOf(v[1].trim()), Integer.valueOf(v[0].trim()));
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		YearMonth ym = (YearMonth) value;
		DecimalFormat monthFormat = new DecimalFormat("00");
		return monthFormat.format(ym.getMonthOfYear()) + " " + SEPARATOR + " " + ym.getYear();
	}
}
